package com.hd.hdxgddcommon.controller;

import com.hd.hdxgddcommon.constant.ResultConst;
import com.hd.hdxgddcommon.entity.dto.ResultDto;
import com.hd.hdxgddcommon.page.MyPage;
import com.hd.hdxgddcommon.utils.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * <p>
 * 控制器 父类
 * </p>
 *
 * @author Administrator
 * @since 2019-03-11
 */
public abstract class AbstractController {


    @InitBinder
    protected void dateBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
        binder.registerCustomEditor(Date.class, editor);
    }

    protected String toPageString(MyPage page) {
        return page != null ? page.toLimitString() : null;
    }

    protected Date stringToDate(String date, SimpleDateFormat sdf) {
        if (StringUtils.isNotBlank(date)) {
            try {
                Date d0 = sdf.parse(date);
                return d0;
            } catch (ParseException e) {
                e.printStackTrace();
                return null;
            }

        }
        return null;
    }


    public final String forward(String url) {
        return "forward:" + url;
    }

    public final String redirect(String url) {
        return "redirect:" + url;
    }

    public final ResultDto success() {
        return new ResultDto(ResultConst.SUCCESS);
    }

    public final ResultDto success(Object data) {
        return new ResultDto(ResultConst.SUCCESS, data);
    }

    public final ResultDto success(int code, String msg, Object data) {
        return new ResultDto(code, msg, data);
    }

    public final ResultDto success(String msg, Object data) {
        return new ResultDto(ResultConst.SUCCESS, msg, data);
    }

    public final ResultDto fail() {
        return new ResultDto(ResultConst.FAIL);
    }

    public final ResultDto fail(String msg) {
        return new ResultDto(ResultConst.FAIL, msg, null);
    }

    public final ResultDto fail(int code, String msg) {
        return new ResultDto(code, msg, null);
    }

    public final ResultDto fail(int code, String msg, Object data) {
        return new ResultDto(code, msg, data);
    }
}
